//
//  MMenuScrollView.swift
//  MMenuScrollView
//
//  Created by huangweiqiang on 2022/6/24.
//

import UIKit
import SnapKit

class MMSegmentScroll: UIView {
    var delegateScroll: ((NSInteger) -> Void)?
    var showIndex: NSInteger = 0
    var scrollView: UIScrollView!
    var titleArray: [String] = []
    var vcArray: [UIView] = []
    var start_offset_x: CGFloat = 0
    var scrollEnd:((NSInteger)->Void)?
    var offsetScale: ((CGFloat)->Void)?
    class func initMMenuScrollView(frame: CGRect, vcArray: [UIView]) -> MMSegmentScroll {
        let aScroll = MMSegmentScroll.init(frame: frame)
        aScroll.vcArray = vcArray
        return aScroll
    }
  
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    
    func initialView() {
        self.scrollView = UIScrollView.init(frame: self.bounds)
        self.scrollView.isPagingEnabled = true
        self.scrollView.delegate = self
        self.scrollView.contentSize = CGSize.init(width: kScreenWidth * CGFloat(self.vcArray.count), height: self.vcArray.first!.frame.size.height)
        self.addSubview(self.scrollView)
        
        for (index, itemView) in self.vcArray.enumerated() {
            itemView.frame.origin.x = CGFloat(index) *  kScreenWidth
            self.scrollView.addSubview(itemView)
        }
    }
    
    ///
    func setContentOffset(x: CGFloat, animation: Bool) {
        UIView.animate(withDuration: 0.24, delay: 0, options: .curveLinear) {
            self.scrollView.contentOffset.x = x
        } completion: { flag in
            //
        }
        let page = x/self.scrollView.frame.size.width
        self.showIndex = NSInteger(page)
        self.delegateScroll?(NSInteger(page))
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension MMSegmentScroll: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let contentOffsetx = scrollView.contentOffset.x 
        self.offsetScale?(contentOffsetx)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        start_offset_x = scrollView.contentOffset.x
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        //print("scrollViewDidEndScrollingAnimation")
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let currentIndex = scrollView.contentOffset.x/self.frame.size.width
        self.scrollEnd?(NSInteger(currentIndex))
    }
}
